Page({
  data: {
    recipeId: null,
    recipeDetail: {},
    isLiked: false,
    isCollected: false,
    loading: true,
    // 评论相关
    comments: [],
    commentText: '',
    userAvatar: 'https://picsum.photos/60/60?random=999'
  },

  onLoad(options) {
    const { id } = options;
    this.setData({
      recipeId: id
    });
    
    this.loadRecipeDetail();
    this.loadComments();
  },

  // 加载食谱详情
  loadRecipeDetail() {
    // 模拟API请求
    setTimeout(() => {
      const mockDetail = this.generateMockDetail(this.data.recipeId);
      this.setData({
        recipeDetail: mockDetail,
        loading: false
      });
    }, 500);
  },

  // 生成模拟详情数据
  generateMockDetail(id) {
    const recipes = {
      1: {
        id: 1,
        type: 2, // 视频模式
        title: '轻食减脂谷物饭',
        imageUrl: 'https://picsum.photos/800/600?random=10',
        videoUrl: 'http://vjs.zencdn.net/v/oceans.mp4',
        authorName: '西瓜',
        authorAvatar: 'https://picsum.photos/60/60?random=1',
        authorId: 1, // 添加作者ID
        cookTime: '15-20分钟',
        difficulty: '简单',
        servings: '1人份',
        likes: 1234,
        description: '这是一道健康美味的轻食减脂谷物饭，营养丰富，口感绝佳。',
        ingredients: [
          { name: '糙米', amount: '1杯', checked: false },
          { name: '藜麦', amount: '1/2杯', checked: false },
          { name: '鸡胸肉', amount: '100g', checked: false },
          { name: '西兰花', amount: '1/2个', checked: false },
          { name: '胡萝卜', amount: '1根', checked: false },
          { name: '橄榄油', amount: '1勺', checked: false }
        ],
        steps: [
          {
            description: '将糙米和藜麦洗净，浸泡30分钟',
            imageUrl: 'https://picsum.photos/300/200?random=20'
          },
          {
            description: '鸡胸肉切丁，用盐和黑胡椒腌制10分钟',
            imageUrl: 'https://picsum.photos/300/200?random=21'
          },
          {
            description: '锅中加水烧开，放入谷物煮熟',
            imageUrl: 'https://picsum.photos/300/200?random=22'
          }
        ],
        tips: [
          '谷物可以提前浸泡，更容易煮熟',
          '鸡胸肉可以用其他蛋白质替代',
          '蔬菜可以根据个人喜好调整'
        ]
      },
      2: {
        id: 2,
        type: 1, // 图文模式
        title: '黑森林巧克力蛋糕',
        imageUrl: 'https://picsum.photos/800/600?random=11',
        authorName: '西瓜',
        authorAvatar: 'https://picsum.photos/60/60?random=2',
        authorId: 1, // 添加作者ID
        cookTime: '60-90分钟',
        difficulty: '中等',
        servings: '8人份',
        likes: 2345,
        description: '经典的黑森林巧克力蛋糕，浓郁的巧克力味搭配樱桃的酸甜，完美！',
        ingredients: [
          { name: '黑巧克力', amount: '200g', checked: false },
          { name: '鸡蛋', amount: '4个', checked: false },
          { name: '糖', amount: '150g', checked: false },
          { name: '面粉', amount: '100g', checked: false },
          { name: '樱桃', amount: '200g', checked: false },
          { name: '淡奶油', amount: '300ml', checked: false }
        ],
        steps: [
          {
            description: '将黑巧克力隔水加热融化',
            imageUrl: 'https://picsum.photos/300/200?random=30'
          },
          {
            description: '鸡蛋和糖打发至蓬松',
            imageUrl: 'https://picsum.photos/300/200?random=31'
          },
          {
            description: '将融化的巧克力加入蛋糊中拌匀',
            imageUrl: 'https://picsum.photos/300/200?random=32'
          }
        ],
        tips: [
          '巧克力要选择品质好的黑巧克力',
          '打发鸡蛋时要注意温度',
          '蛋糕烤好后要完全冷却再装饰'
        ]
      },
      3: {
        id: 3,
        type: 1,
        title: '彩虹水果沙拉',
        imageUrl: 'https://picsum.photos/800/600?random=12',
        authorName: '西瓜',
        authorAvatar: 'https://picsum.photos/60/60?random=3',
        authorId: 1, // 添加作者ID
        cookTime: '10-15分钟',
        difficulty: '简单',
        servings: '4人份',
        likes: 856,
        description: '色彩缤纷的水果沙拉，营养丰富，口感清爽。',
        ingredients: [
          { name: '草莓', amount: '200g', checked: false },
          { name: '蓝莓', amount: '100g', checked: false },
          { name: '橙子', amount: '2个', checked: false },
          { name: '香蕉', amount: '2根', checked: false },
          { name: '葡萄', amount: '200g', checked: false },
          { name: '蜂蜜', amount: '2勺', checked: false }
        ],
        steps: [
          {
            description: '将所有水果洗净切块',
            imageUrl: 'https://picsum.photos/300/200?random=40'
          },
          {
            description: '将水果放入碗中，淋上蜂蜜',
            imageUrl: 'https://picsum.photos/300/200?random=41'
          }
        ],
        tips: [
          '选择新鲜当季的水果',
          '可以根据个人喜好调整水果种类',
          '蜂蜜可以换成其他甜味剂'
        ]
      },
      4: {
        id: 4,
        type: 1,
        title: '燕麦香蕉谷物碗',
        imageUrl: 'https://picsum.photos/800/600?random=13',
        authorName: '西瓜',
        authorAvatar: 'https://picsum.photos/60/60?random=4',
        authorId: 1, // 添加作者ID
        cookTime: '5-10分钟',
        difficulty: '简单',
        servings: '1人份',
        likes: 567,
        description: '营养丰富的燕麦香蕉谷物碗，简单易做，健康美味。',
        ingredients: [
          { name: '燕麦', amount: '1/2杯', checked: false },
          { name: '香蕉', amount: '1根', checked: false },
          { name: '牛奶', amount: '1杯', checked: false },
          { name: '蜂蜜', amount: '1勺', checked: false },
          { name: '坚果', amount: '适量', checked: false }
        ],
        steps: [
          {
            description: '将燕麦和牛奶放入锅中煮至浓稠',
            imageUrl: 'https://picsum.photos/300/200?random=50'
          },
          {
            description: '加入切片的香蕉和蜂蜜',
            imageUrl: 'https://picsum.photos/300/200?random=51'
          }
        ],
        tips: [
          '燕麦可以选择即食燕麦',
          '可以根据个人喜好添加其他水果',
          '坚果可以增加口感和营养'
        ]
      }
    };

    return recipes[id] || recipes[1];
  },

  // 加载评论
  loadComments() {
    // 模拟评论数据
    const mockComments = [
      {
        id: 1,
        avatar: 'https://picsum.photos/60/60?random=100',
        username: '美食爱好者',
        time: '2小时前',
        content: '看起来很好吃，我也要试试！',
        likeCount: 12,
        isLiked: false
      },
      {
        id: 2,
        avatar: 'https://picsum.photos/60/60?random=101',
        username: '烘焙达人',
        time: '1天前',
        content: '步骤很详细，新手也能学会',
        likeCount: 8,
        isLiked: false
      }
    ];

    this.setData({
      comments: mockComments
    });
  },

  // 返回
  onBackTap() {
    wx.navigateBack();
  },

  // 点赞
  onLikeTap() {
    const isLiked = !this.data.isLiked;
    const recipeDetail = { ...this.data.recipeDetail };
    recipeDetail.likes = isLiked ? recipeDetail.likes + 1 : recipeDetail.likes - 1;
    
    this.setData({
      isLiked: isLiked,
      recipeDetail: recipeDetail
    });
  },

  // 收藏
  onCollectTap() {
    const isCollected = !this.data.isCollected;
    this.setData({
      isCollected: isCollected
    });
    
    wx.showToast({
      title: isCollected ? '收藏成功' : '取消收藏',
      icon: 'success'
    });
  },

  // 关注
  onFollowTap() {
    wx.navigateTo({
      url: '/my/pages/editRecipe/editRecipe',
    })
  },

  // 分享
  onShareTap() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  // 评论
  onCommentTap() {
    // 聚焦到评论输入框
    this.setData({
      showCommentInput: true
    });
  },

  // 评论输入
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value
    });
  },

  // 提交评论
  onSubmitComment() {
    if (!this.data.commentText.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    // 模拟提交评论
    const newComment = {
      id: Date.now(),
      avatar: this.data.userAvatar,
      username: '我',
      time: '刚刚',
      content: this.data.commentText,
      likeCount: 0,
      isLiked: false
    };

    const comments = [newComment, ...this.data.comments];
    this.setData({
      comments: comments,
      commentText: '',
      showCommentInput: false
    });

    wx.showToast({
      title: '评论成功',
      icon: 'success'
    });
  },

  // 评论点赞
  onCommentLike(e) {
    const commentId = e.currentTarget.dataset.id;
    const comments = this.data.comments.map(comment => {
      if (comment.id === commentId) {
        return {
          ...comment,
          likeCount: comment.isLiked ? comment.likeCount - 1 : comment.likeCount + 1,
          isLiked: !comment.isLiked
        };
      }
      return comment;
    });

    this.setData({
      comments: comments
    });
  },

  // 点击作者头像 - 跳转到用户详情页
  onAuthorAvatarTap() {
    const authorId = this.data.recipeDetail.authorId || 1; // 默认作者ID为1
    wx.navigateTo({
      url: `/my/pages/user-detail/user-detail?id=${authorId}`
    });
  },

  // 点击评论用户头像 - 跳转到用户详情页
  onCommentUserAvatarTap(e) {
    const userId = e.currentTarget.dataset.userid;
    const username = e.currentTarget.dataset.username;
    
    // 模拟用户ID（实际应该从后端获取）
    const mockUserId = this.getMockUserId(username);
    
    wx.navigateTo({
      url: `/my/pages/user-detail/user-detail?id=${mockUserId}`
    });
  },

  // 获取模拟用户ID（实际应该从后端获取）
  getMockUserId(username) {
    const userMap = {
      '美食爱好者': 2,
      '烘焙达人': 3,
      '我': 1
    };
    return userMap[username] || 1;
  },

  // 食材勾选
  onIngredientCheck(e) {
    const index = e.currentTarget.dataset.index;
    const recipeDetail = { ...this.data.recipeDetail };
    recipeDetail.ingredients[index].checked = !recipeDetail.ingredients[index].checked;
    
    this.setData({
      recipeDetail: recipeDetail
    });
  },

  // 开始烹饪
  onStartCookTap() {
    wx.showToast({
      title: '开始烹饪模式',
      icon: 'success'
    });
  },

  // 格式化时间
  formatTime(date) {
    const now = new Date();
    const target = new Date(date);
    const diff = now - target;
    
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
    
    if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else {
      return `${days}天前`;
    }
  },

  // 分享给朋友
  onShareAppMessage() {
    return {
      title: this.data.recipeDetail.title,
      path: `/my/pages/recipe-detail/recipe-detail?id=${this.data.recipeId}`,
      imageUrl: this.data.recipeDetail.imageUrl
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: this.data.recipeDetail.title
    };
  },

  // 预览图片
  previewImage(e) {
    const current = e.currentTarget.dataset.url;
    const urls = [this.data.recipeDetail.imageUrl];
    
    wx.previewImage({
      current: current,
      urls: urls
    });
  }
}); 